using System.Collections.Generic;
using System.Text;
using UnityEngine;

public class XPluginManager : XMonoSingleton<XPluginManager>
{
    private Dictionary<string, XPlugin> plugins = new Dictionary<string, XPlugin>();

    public XPlugin LoadPlugin(System.Type type)
    {
        if (!plugins.ContainsKey(type.Name))
        {
            GameObject pluginGo = new GameObject(type.Name);
            pluginGo.transform.SetParent(transform, false);

            XPlugin plugin = (XPlugin)pluginGo.AddComponent(type);
            plugin.Install();

            plugins.Add(type.Name, plugin);

        }

        return plugins[type.Name];
    }

    public void UnloadPlugin(System.Type type)
    {
        if (plugins.ContainsKey(type.Name))
        {
            XPlugin plugin = plugins[type.Name];
            plugin.Uninstall();

            plugins.Remove(type.Name);
            Destroy(plugin.gameObject);
        }
    }

    public T LoadPlugin<T>() where T : XPlugin
    {
        string typeName = typeof(T).Name;
        if (!plugins.ContainsKey(typeName))
        {
            GameObject pluginGo = new GameObject(typeName);
            pluginGo.transform.SetParent(transform, false);

            XPlugin plugin = pluginGo.AddComponent<T>();
            plugin.Install();

            plugins.Add(typeName, plugin);
        }

        return (T)plugins[typeName];
    }

    public T QueryPlugin<T>() where T : XPlugin
    {
        return (T)plugins[typeof(T).Name];
    }

    public void UnloadPlugin<T>() where T : XPlugin
    {
        string typeName = typeof(T).Name;
        if (plugins.ContainsKey(typeName))
        {
            T plugin = (T)plugins[typeName];
            plugins.Remove(typeName);

            Destroy(plugin.gameObject);
        }
    }

    public bool FireEvent(int nEventId, XEventArgs args)
    {
#if UNITY_EDITOR
        GLog.Log("Plugin event [<color=red>{0}</color>] <color=yellow>{1}</color>", nEventId, args.ToString());
#endif

        foreach(KeyValuePair<string, XPlugin> it in plugins)
        {
            it.Value.FireEvent(nEventId, args);
        }

        return true;
    }
}
